//
//  StatusCellPictureView.swift
//  01- 搭建框架
//
//  Created by apple on 15/10/20.
//  Copyright © 2015年 任伟. All rights reserved.
//

import UIKit
import SDWebImage

/// 照片之间的间距
private let StatusPictureViewItemMargin: CGFloat = 8

/// 设置可重用表示符
private let StatusPictureCellId = "StatusPictureCellId"

/// MARK: -微博配图视图
class StatusCellPictureView: UICollectionView {

    /// MARK: - 微博视图模型
    var viewModel: StatusViewModel? {
        didSet {
            sizeToFit()
            
            reloadData()
        }
    }
    
    override func sizeThatFits(size: CGSize) -> CGSize {
        return calcViewSize()
    }
    
    /// MARK: - 构造函数
    init() {
    
        let layout = UICollectionViewFlowLayout()
        
        // 设置间距
        layout.minimumInteritemSpacing = StatusPictureViewItemMargin
        layout.minimumLineSpacing = StatusPictureViewItemMargin
        
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        
        backgroundColor = UIColor(white: 0.9, alpha: 1.0)
        
        // 设置数据源
        dataSource = self
        
        // 设置代理
        delegate = self
        
        // 注册 cell
        registerClass(StatusCellPictureViewCell.self, forCellWithReuseIdentifier: StatusPictureCellId)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

/// MARK: - 数据源方法
extension StatusCellPictureView: UICollectionViewDataSource {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return viewModel?.thumbnailUrls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(StatusPictureCellId, forIndexPath: indexPath) as! StatusCellPictureViewCell
        
        cell.imageURL = viewModel!.thumbnailUrls![indexPath.row]
        
        return cell
    }
    
}

/// MARK: - 代理的方法
extension StatusCellPictureView: UICollectionViewDelegate {

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        print("选中了照片\(viewModel?.thumbnailUrls![indexPath.item])")
        
        // 测试
       // photoBrowserPresentFromRect(indexPath)
       // photoBrowserPresentToRect(indexPath)
        
        // 发送通知
        NSNotificationCenter.defaultCenter().postNotificationName(WBStatusSelectedPhotoNotification,
            object: self,
            userInfo: [WBStatusSelectedPhotoURLsKey : viewModel!.thumbnailUrls!, WBStatusSelectedPhotoIndexPathKey : indexPath ])
    }
}

/// MARK: - 照片查看器的展现协议 PhotoBrowserPresentDelegate
extension StatusCellPictureView: PhotoBrowserPresentDelegate {
    
    // 创建一个 imageView 在参与动画
    func imageViewForPresent(indexPath: NSIndexPath) -> UIImageView {
        
        let iv = UIImageView()
        
        // 1. 设置内容的填充模式
        iv.contentMode = .ScaleAspectFill
        iv.clipsToBounds = true
        
        // 2. 设置图像（缩略图）
        if let url = viewModel?.thumbnailUrls?[indexPath.item]{
        
            iv.sd_setImageWithURL(url)
        }
        
        return iv
    }
    
    func photoBrowserPresentFromRect(indexPath: NSIndexPath) -> CGRect {
        
        // 1. 根据 indexPath 获取当前用户选择的 cell
        let cell = self.cellForItemAtIndexPath(indexPath)!
        
        // 2. 通过 cell 知道 cell 对应在屏幕上的准确位置
        let rect = self.convertRect(cell.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
        
//        let v = imageViewForPresent(indexPath)
//        v.frame = rect
//        UIApplication.sharedApplication().keyWindow?.addSubview(v)
//        print(cell)
        
        return rect
    }
    
    // 目标位置
    func photoBrowserPresentToRect(indexPath: NSIndexPath) -> CGRect {
        
        // 根据缩略图的大小，等比例计算目标位置
        guard let key = viewModel?.thumbnailUrls?[indexPath.item].absoluteString else {
            return CGRectZero
        }
        
        // 从 sdwebImge 获取本地缓存图片
        guard let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key) else {
            return CGRectZero
        }
        
        // 根据图像的大小，计算全屏的大小
        let w = UIScreen.mainScreen().bounds.width
        let h = image.size.height * w / image.size.width
        
        // 对高度进行额外的处理
        let screnHeight = UIScreen.mainScreen().bounds.height
        var y: CGFloat = 0
        if h < screnHeight {
        
            y = (screnHeight - h) * 0.5
        }
        // 测试位置
        let rect = CGRect(x: 0, y: y, width: w, height: h)
//        let v = imageViewForPresent(indexPath)
//        v.frame = rect
//        
//        UIApplication.sharedApplication().keyWindow?.addSubview(v)
        
        return rect
    }
}

/// MARK: -计算视图大小
extension StatusCellPictureView {

    // 计算视图的大小
    private func calcViewSize() -> CGSize {
        
        // 1. 准备
        // 每行的照片的数量
        let rowCount: CGFloat = 3
        let maxWidth = UIScreen.mainScreen().bounds.width - 2 * StatusCellMargin - 1
        let itemWidth = (maxWidth - 2 * StatusPictureViewItemMargin) / rowCount
        
        // 2. 设置
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        
        // 3.获取图片的数量
        let count = viewModel?.thumbnailUrls?.count ?? 0
        
        // 计算的开始
        if count == 0 {
            return CGSizeZero
        }
        
        if count == 1 {
            var size = CGSize(width: 150, height: 120)
            
            // 提取单张图片
            if let key = viewModel?.thumbnailUrls?.first?.absoluteString {
            
                size = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key).size
            }
            
            // 图片过窄的处理
            size.width = size.width < 40 ? 40 : size.width
            
            // 图片过宽的处理
            if size.width > 300 {
            
                let w: CGFloat = 300
                let h = size.height * w / size.width
                
                size = CGSize(width: w, height: h)
            }
            
            
            layout.itemSize = size
            return size
        }
        
        if count == 4 {
            let w = 2 * itemWidth + StatusPictureViewItemMargin
            return CGSize(width: w, height: w)
        }
        
        let row = CGFloat((count - 1) / Int(rowCount) + 1)
        let h = row * itemWidth + (row - 1) * StatusPictureViewItemMargin
        let w = rowCount * itemWidth + (rowCount - 1) * StatusPictureViewItemMargin
        
        return CGSize(width: w, height: h)
    }
}

/// MARK: - 微博配图
private class StatusCellPictureViewCell: UICollectionViewCell {

    var imageURL: NSURL? {
        didSet {
            iconView.sd_setImageWithURL(imageURL,
                placeholderImage: nil,
                options: [SDWebImageOptions.RetryFailed,
                    SDWebImageOptions.RefreshCached])
        }
    }
    
    // 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        // 添加控件
        contentView.addSubview(iconView)
        
        // 自动布局
        iconView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // - 懒加载控件 (设置填充模式) 
    private lazy var iconView: UIImageView = {
        let iv = UIImageView()
        
        iv.contentMode = .ScaleAspectFill
        iv.clipsToBounds = true
        
        return iv
    }()
}
